import { Avatar, Box, Group, Text, rem } from "@mantine/core";
import { Dropzone, MIME_TYPES } from "@mantine/dropzone";
import { notifications } from "@mantine/notifications";
import { IconPhoto, IconUpload, IconX } from "@tabler/icons-react";
import { useState } from "react";
import { useAPIUtils } from "./APIUtilsProvider";

export function WithwingsDropzone({
  maxSize = 3,
  src,
  text = "点击或拖入框中",
  accept = [MIME_TYPES.png, MIME_TYPES.jpeg],
  onSuccess,
}) {
  const [loading, setLoading] = useState(false);

  const { filePOST } = useAPIUtils();

  const upload = async (files) => {
    if (!files[0]) return;

    setLoading(true);
    const { url } = await filePOST("/api/admin/files", files[0]);
    onSuccess(url);
    setLoading(false);
  };

  return (
    <Box m={"lg"}>
      <Dropzone
        loading={loading}
        multiple={false}
        onDrop={upload}
        onReject={(files) =>
          notifications.show({
            title: "文件不符合要求，请检查大小和类型",
            color: "red",
          })
        }
        maxSize={maxSize * 1024 ** 2}
        accept={accept}
      >
        <Group
          justify="center"
          gap="xl"
          mih={220}
          style={{ pointerEvents: "none" }}
        >
          <Dropzone.Accept>
            <IconUpload
              style={{
                width: rem(52),
                height: rem(52),
                color: "var(--mantine-color-blue-6)",
              }}
              stroke={1.5}
            />
          </Dropzone.Accept>
          <Dropzone.Reject>
            <IconX
              style={{
                width: rem(52),
                height: rem(52),
                color: "var(--mantine-color-red-6)",
              }}
              stroke={1.5}
            />
          </Dropzone.Reject>
          <Dropzone.Idle>
            {src ? (
              <Avatar src={src} size={rem(100)} radius={"xs"} />
            ) : (
              <IconPhoto
                style={{
                  width: rem(100),
                  height: rem(100),
                  color: "var(--mantine-color-dimmed)",
                }}
                stroke={1.5}
              />
            )}
          </Dropzone.Idle>

          <div>
            <Text size="l" inline>
              {text}
            </Text>
            <Text size="sm" c="dimmed" inline mt={7}>
              {`文件不能超过指定大小 ${maxSize} MB`}
            </Text>
          </div>
        </Group>
      </Dropzone>
    </Box>
  );
}
